package com.example.ai.inventory.service;

import com.example.ai.inventory.entity.Category;
import com.example.ai.inventory.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品分类服务实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    
    @Autowired
    private CategoryRepository categoryRepository;
    
    @Override
    public List<Category> getAllCategories() {
        List<Category> allCategories = categoryRepository.findAll();
        return buildCategoryTree(allCategories);
    }
    
    @Override
    public Category getCategoryById(Long id) {
        return categoryRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("分类不存在：" + id));
    }
    
    @Override
    public Category addCategory(Category category) {
        // 验证分类名称是否重复
        List<Category> existingCategories = categoryRepository.findByNameContaining(category.getName());
        for (Category existing : existingCategories) {
            if (existing.getName().equals(category.getName()) && existing.getParentId().equals(category.getParentId())) {
                throw new RuntimeException("同级分类名称已存在：" + category.getName());
            }
        }
        return categoryRepository.save(category);
    }
    
    @Override
    public Category updateCategory(Category category) {
        // 验证分类是否存在
        Category existing = getCategoryById(category.getId());
        
        // 验证分类名称是否重复
        List<Category> existingCategories = categoryRepository.findByNameContaining(category.getName());
        for (Category c : existingCategories) {
            if (c.getName().equals(category.getName()) && 
                c.getParentId().equals(category.getParentId()) && 
                !c.getId().equals(category.getId())) {
                throw new RuntimeException("同级分类名称已存在：" + category.getName());
            }
        }
        
        return categoryRepository.save(category);
    }
    
    @Override
    public void deleteCategory(Long id) {
        // 检查是否有子分类
        List<Category> children = categoryRepository.findByParentId(id);
        if (!children.isEmpty()) {
            throw new RuntimeException("该分类下有子分类，无法删除");
        }
        
        categoryRepository.deleteById(id);
    }
    
    @Override
    public List<Category> getCategoriesByParentId(Long parentId) {
        return categoryRepository.findByParentId(parentId);
    }
    
    @Override
    public List<Category> searchCategories(String keyword) {
        return categoryRepository.findByNameContaining(keyword);
    }
    
    /**
     * 构建分类树形结构
     */
    private List<Category> buildCategoryTree(List<Category> allCategories) {
        Map<Long, Category> categoryMap = new HashMap<>();
        List<Category> rootCategories = new ArrayList<>();
        
        // 将所有分类放入Map中
        for (Category category : allCategories) {
            category.setChildren(new ArrayList<>());
            categoryMap.put(category.getId(), category);
        }
        
        // 构建树形结构
        for (Category category : allCategories) {
            if (category.getParentId() == 0) {
                // 根节点
                rootCategories.add(category);
            } else {
                // 子节点
                Category parent = categoryMap.get(category.getParentId());
                if (parent != null) {
                    parent.getChildren().add(category);
                }
            }
        }
        
        return rootCategories;
    }
}